/**
 * API 测试脚本
 * 用于测试配置管理 API 是否正常工作
 */

const http = require('http');

const SERVER_URL = 'http://localhost:3000';

// 发送 HTTP 请求的辅助函数
function makeRequest(method, path, data = null) {
    return new Promise((resolve, reject) => {
        const url = new URL(path, SERVER_URL);
        const options = {
            hostname: url.hostname,
            port: url.port,
            path: url.pathname,
            method: method,
            headers: {
                'Content-Type': 'application/json',
            }
        };

        const req = http.request(options, (res) => {
            let body = '';
            res.on('data', (chunk) => {
                body += chunk;
            });
            res.on('end', () => {
                try {
                    const response = JSON.parse(body);
                    resolve({ status: res.statusCode, data: response });
                } catch (e) {
                    resolve({ status: res.statusCode, data: body });
                }
            });
        });

        req.on('error', (error) => {
            reject(error);
        });

        if (data) {
            req.write(JSON.stringify(data));
        }

        req.end();
    });
}

// 测试函数
async function runTests() {
    console.log('🧪 开始测试配置管理 API...\n');

    try {
        // 测试 1: 健康检查
        console.log('📋 测试 1: 健康检查');
        const healthCheck = await makeRequest('GET', '/health');
        if (healthCheck.status === 200 && healthCheck.data.status === 'ok') {
            console.log('✅ 健康检查通过\n');
        } else {
            console.log('❌ 健康检查失败\n');
            return;
        }

        // 测试 2: 获取配置
        console.log('📋 测试 2: 获取配置');
        const getConfig = await makeRequest('GET', '/api/config');
        if (getConfig.status === 200 && getConfig.data.errcode === 0) {
            console.log('✅ 获取配置成功');
            console.log('当前配置:', JSON.stringify(getConfig.data.data, null, 2));
            console.log();
        } else {
            console.log('❌ 获取配置失败');
            console.log('响应:', getConfig);
            console.log();
        }

        // 测试 3: 更新配置 (错误密码)
        console.log('📋 测试 3: 更新配置 (错误密码)');
        const updateConfigWrongPassword = await makeRequest('POST', '/api/admin/config', {
            webhost: 'http://test.com',
            adminPassword: 'wrong_password'
        });
        if (updateConfigWrongPassword.status === 401) {
            console.log('✅ 密码验证正常工作\n');
        } else {
            console.log('❌ 密码验证失败\n');
        }

        // 测试 4: 更新配置 (正确密码)
        console.log('📋 测试 4: 更新配置 (正确密码)');
        const updateConfig = await makeRequest('POST', '/api/admin/config', {
            webhost: 'http://test-update.com',
            webviewUrl: 'https://test-webview.com',
            addon_name: 'test',
            adminPassword: 'admin123'
        });
        if (updateConfig.status === 200 && updateConfig.data.errcode === 0) {
            console.log('✅ 更新配置成功');
            console.log('新配置:', JSON.stringify(updateConfig.data.data, null, 2));
            console.log();
        } else {
            console.log('❌ 更新配置失败');
            console.log('响应:', updateConfig);
            console.log();
        }

        // 测试 5: 验证配置已更新
        console.log('📋 测试 5: 验证配置已更新');
        const verifyConfig = await makeRequest('GET', '/api/config');
        if (verifyConfig.status === 200 && 
            verifyConfig.data.data.webhost === 'http://test-update.com' &&
            verifyConfig.data.data.version > 1) {
            console.log('✅ 配置更新验证成功');
            console.log('版本号已递增:', verifyConfig.data.data.version);
            console.log();
        } else {
            console.log('❌ 配置更新验证失败\n');
        }

        // 恢复原始配置
        console.log('📋 恢复原始配置...');
        await makeRequest('POST', '/api/admin/config', {
            webhost: 'http://qm.lr12.com',
            webviewUrl: 'https://mall.yishanglv.cn/addons/yun_shop/?menu#/newDiy?page_id=885&i=136',
            addon_name: 'qm',
            adminPassword: 'admin123'
        });
        console.log('✅ 配置已恢复\n');

        console.log('🎉 所有测试完成!');

    } catch (error) {
        console.error('❌ 测试过程中出错:', error.message);
        console.log('\n请确保配置服务器正在运行: npm start');
    }
}

// 运行测试
runTests();

